import { h, createApp } from 'vue';
import { Quill } from '@vueup/vue-quill';
import EmbeddableChart from './EmbeddableChart.vue';

const BlockEmbed = Quill.import('blots/block/embed');

class ChartBlot extends BlockEmbed {
  static create(value) {
    const node = super.create();
    node.setAttribute('contenteditable', false);
    node.setAttribute('data-chart', '');
    node.setAttribute('data-options', JSON.stringify(value));
    
    // Create a container for the Vue component
    const container = document.createElement('div');
    container.className = 'chart-container';
    node.appendChild(container);
    
    // Mount the Vue component
    Promise.resolve().then(() => {
      if (container.isConnected) {
        const app = createApp(EmbeddableChart, {
          options: value,
          width: '100%',
          height: '300px'
        });
        app.mount(container);
        node._vueApp = app;
      }
    });
    
    return node;
  }

  static value(node) {
    try {
      return JSON.parse(node.getAttribute('data-options'));
    } catch (error) {
      console.error('Error parsing chart options:', error);
      return null;
    }
  }

  detach() {
    if (this.domNode._vueApp) {
      this.domNode._vueApp.unmount();
      delete this.domNode._vueApp;
    }
    super.detach();
  }
}

ChartBlot.blotName = 'chart';
ChartBlot.tagName = 'div';
ChartBlot.className = 'embedded-chart-blot';

export default ChartBlot;
